#pragma once

#include <iostream>
#include <string>
#include <functional>
#include "Socket.hpp"
#include "Tcpserver.hpp"
#include "Log.hpp"
#include "HttpProtocol.hpp"

using namespace SocketMoudle;
using namespace TcpserverMoudle;
using namespace LogMoudle;

using http_handler_t = std::function<void(HttpRequest &, HttpReponse &)>;

class HttpServer
{

private:
    std::unique_ptr<Tcpserver> _tsver;
    std::unordered_map<std::string, http_handler_t> _route;

public:
    HttpServer(int port) : _tsver(std::make_unique<Tcpserver>(port))
    {
    }

    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }

    void Start()
    {
        _tsver->InitServer([this](SockPtr sockfd, InetAddr client)
                           { return this->Hander_request(sockfd, client); });

        _tsver->Loop();
    }

    bool SafeCheck(const std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    bool Hander_request(SockPtr sockfd, InetAddr client)
    {
        LOG(Logevel::INFO) << "get a new clinet , clinet info : " << sockfd->Fd() << " addr info: " << client.PrintDebug();

        std::string http_request;
        sockfd->Recv(&http_request);

        // 这个类型还没定义
        HttpRequest req;
        req.Deserialize(http_request);
        HttpReponse resp;

        // 请求应该被分为两类：1.请求一般的静态资源  2.提交参数，携带参数，需要进行交互设置
        if (req.IsHasArgs())
        {
            

            LOG(Logevel::INFO)<<"--------------------IsHasArgs()";

            std::string service = req.Path();

            if (SafeCheck(service))
                _route[req.Path()](req, resp);
            else
                resp.Build(req);
        }
        else
        {
            
            LOG(Logevel::INFO)<<"---------------Non IsHasArgs()";
            resp.Build(req);
        }

        std::string resp_str;
        resp.Serialize(&resp_str);

        sockfd->Send(resp_str);

        // std::string statue_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        // std::string body = "<!DOCTYPE html>\
        //                    <html>\
        //                    <head>\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                    <h1>xiao wang ai he shu yi</ h1>\
        //                    </body> </html > ";

        // std::string Http_Resopnse = statue_line + body;
        // sockfd->Send(Http_Resopnse);

        return true;
    }

    ~HttpServer() {}
};
